package com.tim.app.ui.fragment.message;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.db.dao.DaoFactory;
import com.tim.app.server.entry.Answer;
import com.tim.app.server.entry.Article;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.entry.Notice;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.entry.Story;
import com.tim.app.server.entry.User;
import com.tim.app.ui.activity.DynamicDetailActivity;
import com.tim.app.ui.activity.StoryDetailActivity;
import com.tim.app.ui.activity.selected.AnswerDetailActivity;
import com.tim.app.ui.activity.selected.ArticleDetailActivity;
import com.tim.app.ui.activity.selected.CommentDetailActivity;
import com.tim.app.ui.activity.selected.QuestionAndAnswerDetailActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.ui.adapter.message.NoticeAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * 通知页面
 */
public class NoticeFragment extends BaseFragment implements LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "NoticeFragment";
    private View rootView;

    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvNotice;
    private EmptyLayout emptyLayout;
    private NoticeAdapter adapter;
    private List<Notice> dataList;
    private int totalNoticeCount;

    String type;

    public static NoticeFragment newInstance(String type) {
        NoticeFragment newFragment = new NoticeFragment();
        Bundle bundle = new Bundle();
        bundle.putString("type", type);
        newFragment.setArguments(bundle);
        return newFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_notice, container, false);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvNotice = (WrapRecyclerView) rootView.findViewById(R.id.wrvNotice);

            wrvNotice.setOverScrollMode(View.OVER_SCROLL_NEVER);
            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            emptyLayout = new EmptyLayout(getActivity(), load_more);

            emptyLayout.showLoading();
            emptyLayout.setEmptyDrawable(R.drawable.ic_empty_notice);
            emptyLayout.setEmptyText("你还没有收到通知", "");

            if (dataList == null) {
                dataList = new ArrayList<>();
            }
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvNotice.setLayoutManager(layoutManager);

            adapter = new NoticeAdapter(getActivity(), dataList);
            adapter.setOnItemClickListener(this);
            wrvNotice.setAdapter(adapter);
            Bundle args = getArguments();
            if (args != null) {
                type = args.getString("type");
            }
        }

        loadNoitceMessage(type);
        EventManager.ins().registListener(EventTag.ON_NEW_NOTICE, eventListener);
        totalNoticeCount = DaoFactory.getNoticeDao().getNoticeCount();
        return rootView;
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_NEW_NOTICE:
                    Notice notice = (Notice) dataobj;
                    String typeValue = "";
                    if (notice.getOperation().equals("action")) {
                        typeValue = notice.getActionType();
                    } else {
                        typeValue = notice.getOperation();
                    }
                    if (typeValue.equals(type)) {
                        totalNoticeCount = DaoFactory.getNoticeDao().getNoticeCount();
                        dataList.add(0, notice);
                        adapter.notifyDataSetChanged();
                    }
                    break;
            }
        }
    };

    public void loadNoitceMessage(String type) {
        final List<Notice> noticeList = DaoFactory.getNoticeDao().getNotices(AppKey.PAGE_SIZE, type);
        if (null != noticeList && noticeList.size() > 0) {
            dataList.clear();
            dataList.addAll(noticeList);
            adapter.notifyDataSetChanged();
            emptyLayout.showContent();
            if (dataList.size() < totalNoticeCount) {
                load_more.loadMoreFinish(false, true);
            } else {
                load_more.loadMoreFinish(false, false);
            }
        } else {
            emptyLayout.showEmpty();
            load_more.loadMoreFinish(false, false);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        Notice notice = dataList.get(position);
        if (notice.getOperation().equals("action")) {
            if (notice.getActionType().equals("agree")) {
                if (notice.getType().equals(AppKey.TYPE_STORY)) {
                    Story story = new Story();
                    story.setId(notice.getTypeId());
                    story.setTitle(notice.getTitle());
                    ArrayList<Story> list = new ArrayList<>();
                    list.add(story);
                    StoryDetailActivity.start(getActivity(), list, 0, false);
                } else if (notice.getType().equals(AppKey.TYPE_ANSWER)) {
                    Answer answer = new Answer();
                    answer.setId(notice.getTypeId());
                    answer.setTitle(notice.getTitle());
                    AnswerDetailActivity.start(getActivity(), answer, false);
                } else if (notice.getType().equals(AppKey.TYPE_DYNAMIC)) {
                    Dynamic dynamic = new Dynamic();
                    dynamic.setId(notice.getTypeId());
                    dynamic.setTitle(notice.getTitle());
                    DynamicDetailActivity.start(getActivity(), dynamic, false);
                } else if (notice.getType().equals(AppKey.TYPE_ARTICLE)) {
                    Article article = new Article();
                    article.setId(notice.getTypeId());
                    article.setTitle(notice.getTitle());
                    article.setDigest(notice.getDigest());
                    ArticleDetailActivity.start(getActivity(), article, false);
                } else if (notice.getType().equals(AppKey.TYPE_COMMENT)) {
                    CommentDetailActivity.start(getActivity(), notice.getTypeId(), false);
                }
            } else {
                Problem problem = new Problem();
                problem.setId(notice.getTypeId());
                QuestionAndAnswerDetailActivity.start(getActivity(), problem, false);
            }
        } else if (notice.getOperation().equals("comment")) {
            if (AppKey.TYPE_COMMENT.equals(notice.getType())) {
                CommentDetailActivity.start(getActivity(), notice.getTypeId(), false);
            } else {
                CommentDetailActivity.start(getActivity(), notice.getOperationId(), false);
            }
        } else if (notice.getOperation().equals("answer")) {
            Answer answer = new Answer();
            answer.setId(notice.getOperationId());
            answer.setTitle(notice.getTitle());
            answer.setProblemId(notice.getProblemId());
            AnswerDetailActivity.start(getActivity(), answer, false);
        } else if (notice.getOperation().equals("concern")) {
            User user = new User();
            user.setUserId(notice.getUser().getUserId());
            user.setName(notice.getUser().getNick());
            user.setImage(notice.getUser().getImg());
            SomeoneHomepageActivity.start(getActivity(), user, false);
        } else if (notice.getOperation().equals("flower")) {
            User user = new User();
            user.setUserId(notice.getUser().getUserId());
            user.setName(notice.getUser().getNick());
            user.setImage(notice.getUser().getImg());
            SomeoneHomepageActivity.start(getActivity(), user, false);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
        EventManager.ins().removeListener(EventTag.ON_NEW_NOTICE, eventListener);
    }

    private void loadMoreData() {
        if (dataList != null && dataList.size() > 0) {
            final List<Notice> noticeList = DaoFactory.getNoticeDao().getNoticeByTime(dataList.get(dataList.size() - 1).getTime(), AppKey.PAGE_SIZE, type);
            if (null != noticeList && noticeList.size() > 0) {
                dataList.addAll(noticeList);
                adapter.notifyDataSetChanged();
                if (dataList.size() < totalNoticeCount) {
                    load_more.loadMoreFinish(false, true);
                } else {
                    load_more.loadMoreFinish(false, false);
                }
            } else {
                load_more.loadMoreFinish(false, false);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        loadMoreData();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
